package com.zjj.filmcommentapi.utils;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 操作redis的工具类
 */
@Component
public   class  RedisUtil {
    //操作字符串的template，StringRedisTemplate是RedisTemplate的一个子集
    @Resource(name = "stringRedisTemplate")
     StringRedisTemplate stringRedisTemplate;
//    private Logger logger= LoggerFactory.getLogger(RedisUtil.class);
    @Resource(name = "redisTemplate")
     RedisTemplate<Object,Object> redisTemplate;
    // 判断key是否存在
    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
    // 储存
    public  void set(String key,String value){
        ValueOperations<Object,Object> ops = redisTemplate.opsForValue();
            ops.set(key,value);
    }
    // 查询
    public  String get(String key){
        return (String) redisTemplate.opsForValue().get(key);
    }
    // 删除
    public  void del(String key){
        redisTemplate.delete(key);
    }
    // 储存对象类型
    public  void sentinelSet(String key,Object object){
        redisTemplate.opsForValue().set(key,object);
    }
    // 查询对象类型
    public  Object sentinelGet(String key){
        return redisTemplate.opsForValue().get(key);
    }
    //重新设置缓存过期时间
    public  String renewToken(String key, Object obj) {
        redisTemplate.opsForValue().set(key,obj);
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return key;
    }
    // 得到剩余失效时间
    public  Long getTokenExpire(String key){
        long time = redisTemplate.getExpire(key);
        return time;
    }
    // 储存list 先进先出
    public void addTokenList(String key,String item){
        redisTemplate.opsForList().rightPush(key,item);
    }
    // 删除list 删除最前面一个
    public void delTokenList(String key){
        redisTemplate.opsForList().leftPop(key);
    }
    // 得到list的长度
    public  long getListSize(String key){
        return redisTemplate.opsForList().size(key);
    }
    // 根据条件的到list
    public List getList(String key,long start, long end){
        return redisTemplate.opsForList().range(key,start,end);
    }
    // 根据条件裁剪
    public void listTrim(String key,long start, long end){
        redisTemplate.opsForList().trim(key,start,end);
    }
    // 根据条件删除list中的元素
    public void removeListItem(String key, long count, Object value){
        redisTemplate.opsForList().remove(key,count,value);
    }
}
